# -*- coding: utf-8 -*-

# 随机 变化 属性和方法的位置
# 方法中添加垃圾代码


import random
import os
import re
import addRandomUI
import addRubbishCode
import PathConfig

#设置属性的位置 随机变化



def m_addRandomRubbish(spaceStr = '\t'):

	if spaceStr == '':
		spaceStr = '\t'

 	name1 = addRandomUI.getRandomStr(random.randint(2,4))
 	name2 = addRandomUI.getRandomStr(random.randint(2,4))
 	while name1 == name2:
 		name2 = addRandomUI.getRandomStr(random.randint(2,4))

 	string = '\n'
 	string += spaceStr
 	isClass = False
 	appendclass = addRandomUI.addRandomAppendClass()
 	if appendclass.find('*') >= 0:
 		isClass = True
 		string += appendclass + ' ' +  name1 + ' = [' + appendclass.replace('*','') + 'new]; \n'  
 	else:
 		string += appendclass + ' ' + name1 + ' = '
 		if appendclass == 'CGFloat':
 			string += str(random.uniform(0.1,1000)) + ';\n'
 		elif appendclass == 'NSInteger':
 			string += str(random.randint(1,1000)) + ';\n'
		elif appendclass == 'CGSize':
			string += 'CGSizeMake(' + str(random.randint(1,1000)) + ',' + str(random.randint(1,1000)) + ');\n'
		elif appendclass == 'CGPoint':
			string += 'CGPointMake(' + str(random.randint(1,1000)) + ',' + str(random.randint(1,1000)) + ');\n'
		elif appendclass == 'CGRect':
			string += 'CGRectMake(' + str(random.randint(1,1000)) + ',' + str(random.randint(1,1000)) + ',' + str(random.randint(1,1000)) + ',' + str(random.randint(1,1000)) +  ');\n'


	string += spaceStr
	ran_type = random.randint(0,1)
	if ran_type == 0:
		string += 'NSMutableArray * ' + name2 + ' = [NSMutableArray new];\n'  + spaceStr
		if isClass:
			string += '[%s addObject:%s];\n' % (name2, name1) 
		else:
			string += '[%s addObject:@(%s)];\n' % (name2, name1)
	else:
		string += 'NSMutableDictionary * %s = [NSMutableDictionary new];\n' % (name2) + spaceStr
		if isClass:
			string += '[%s setObject:%s forKey:@"%s"];\n' % (name2, name1,name1)
		else:
			string += '[%s setObject:@(%s) forKey:@"%s"];\n' % (name2, name1,name1)


	return string

# 添加方法内的垃圾代码
def m_willAddRubbishAtLine(line):
	if line.find('return') >=0 :
		return line
	# 有：下  有= 号 不是== 号   或者 【】
	if line.find(';') < 0:
		return line

	rand_create = random.randint(0,2)
	if rand_create < 2:
		return line 

	# 左边空格串
	rub_str = line
	leftspcae = ''
	while line.startswith(leftspcae  + ' '):
		leftspcae += ' '

	if line.find('=') >=0 and line.find('==') < 0:
		rub_str += m_addRandomRubbish(leftspcae)

	elif line.find('[') >= 0 and line.count('[') == line.count(']'):
		rub_str += m_addRandomRubbish(leftspcae)

	return rub_str		


# 添加方法内的垃圾代码
def h_willAddRubbishAtLine(line):

	return line

	rand_create = random.randint(0,2)
	if rand_create < 2:
		return line

	classArray = ['NSString', 'UILabel', 'NSDictionary', 'NSMutableDictionary', 'NSData', 'UIScrollView', 'UIView', 'UITextView',
                  'UITableView', 'UIImageView', 'NSArray', 'NSMutableArray', 'NSNumber', 'UITextField']
	basicArray = ['CGFloat','NSInteger','CGSize','CGPoint','CGRect']
	listAll = classArray + basicArray

	nameStr = addRandomUI.getRandomStr(random.randint(1,2))
	className = random.choice(listAll)

	rub_str = line
	if className in basicArray: 
		rub_str += '\n\n@property(nonatomic, assign) '+className +' '+nameStr+';'                
	else:
		rub_str += '\n\n@property(nonatomic, retain) '+className +' * _Nullable '+nameStr+';'

	return rub_str



def mran(file_path):
	with open(file_path) as f:
		file_str = f.read()

	# print file_str
	ran_str = ''
	#h的行数组
	hlist = file_str.split('\n')
	# 变换位置的属性
	r_p_list = []
	r_m_list = []
	renter = False
	menter = False
	preline = ''
	for line in hlist:
		# 如果有 // { } 这种注释剔除
		if line.find('//') >= 0:
		 # and (line.find('{') >= 0 or line.find('}') >= 0):
			# line.replace('{','[')
			# line.replace('}',']')
			# print('这段代码注释被删除 ->  ' + line + '')
			preline += line + '\n'
		else:
			if menter:
				preline += m_willAddRubbishAtLine(line) + '\n'
			else:
				preline += line + '\n'

		if line.startswith('@interface'):
			ran_str += preline + '\n'
			renter = True
			preline = ''
		if line.startswith('@implementation'):
			ran_str += preline
			menter = True
			preline = ''
		elif line.startswith('@end'):
			random.shuffle(r_p_list)
			ran_str += ''.join(r_p_list)
			r_p_list = []

			random.shuffle(r_m_list)
			ran_str += ''.join(r_m_list)
			r_m_list = []

			menter = False
			renter = False
			ran_str += preline
			preline = ''
		else:
			if renter:
				if preline.find('{') >= 0:
					if preline.count('{') == preline.count('}'):
						ran_str = ran_str.rstrip('\n')
						ran_str += preline
						preline = ''
				if line.startswith('@property') and line.endswith(';'):
					r_p_list.append(preline)
					preline = ''
				if preline.startswith('@property') and preline.endswith(';'):
					r_p_list.append(preline)
					preline = ''

				
				if line.startswith('-') and line.endswith(';'):
					r_m_list.append(preline)
					preline = ''
				if preline.startswith('-') and preline.endswith(';'):
					r_m_list.append(preline)
					preline = ''
				if line.startswith('+') and line.endswith(';'):
					r_m_list.append(preline)
					preline = ''
				if preline.startswith('+') and preline.endswith(';'):
					r_m_list.append(preline)
					preline = ''

			elif menter: 
				
				if preline.find('/*') >= 0:
					if preline.find('*/\n') >= 0:
						ran_str += preline
						preline = ''
				elif preline.find('{') >= 0 and preline.count('{') == preline.count('}'):
					# print('=========' + preline)
					if preline.startswith('{'):
						ran_str += preline
						preline = ''
					# 过滤旧的垃圾代码
					elif preline.find(PathConfig.filter_rub) < 0:
						r_m_list.append(preline)
					
					preline = ''

			else:
				# 直接附加
				ran_str += preline
				preline = ''

	# with open(file_path.replace('.m','pp.m'), 'w') as f:
	with open(file_path, 'w') as f:
		f.write(ran_str)



def hran(file_path):
	with open(file_path) as f:
		file_str = f.read()

	# print file_str
	ran_str = ''
	#h的行数组
	hlist = file_str.split('\n')
	# 变换位置的属性
	r_p_list = []
	r_m_list = []
	renter = False
	preline = ''
	for line in hlist:
		# 添加垃圾代码  过滤 旧的垃圾代码
		if line.find(PathConfig.filter_rub) < 0:
			if renter and line.startswith('@property') and line.endswith(';'):
				preline += h_willAddRubbishAtLine(line) + '\n'
			else:
				preline += line + '\n'
			
		if line.startswith('@interface'):
			ran_str += preline + '\n'
			renter = True
			preline = ''
		elif line.startswith('@end'):
			random.shuffle(r_p_list)
			ran_str += ''.join(r_p_list)
			r_p_list = []

			random.shuffle(r_m_list)
			ran_str += ''.join(r_m_list)
			r_m_list = []

			renter = False
			ran_str += preline
			preline = ''
		else:
			if renter:
				if line.startswith('@property') and line.endswith(';'):
					r_p_list.append(preline)
					preline = ''
				if preline.startswith('@property') and preline.endswith(';'):
					r_p_list.append(preline)
					preline = ''

				
				if line.startswith('-') and line.endswith(';'):
					r_m_list.append(preline)
					preline = ''
				if preline.startswith('-') and preline.endswith(';'):
					r_m_list.append(preline)
					preline = ''
				if line.startswith('+') and line.endswith(';'):
					r_m_list.append(preline)
					preline = ''
				if preline.startswith('+') and preline.endswith(';'):
					r_m_list.append(preline)
					preline = ''
			else:
				# 直接附加
				ran_str += preline
				preline = ''

	# with open(file_path.replace('.h','bak'), 'w') as f:
	# 	f.write(ran_str)

	with open(file_path, 'w') as f:
		f.write(ran_str)





def randomCode(file_path):


	if '.h' in file_path:
		hran(file_path)
	if '.m' in file_path:
		mran(file_path)



def traverse(file_dir):
	fs = os.listdir(file_dir)
	for dir in fs:
		if dir.startswith('.'):
			#过滤隐藏
			continue
		
		tmp_path = os.path.join(file_dir, dir)
		if not os.path.isdir(tmp_path):
			if dir.startswith(PathConfig.file_pre_class_type):
				#开始处理 查找h和m文件
				randomCode(tmp_path)
		else:
			#继续递归
			traverse(tmp_path)


def main():

	# 添加垃圾代码
	# addRubbishCode.addRubbish()

	# h m 文件修改
	traverse(PathConfig.rub_filepath)
	print('Finish done')

	
if __name__ == '__main__':
	main()